/*
*    SVPWM program
*    By Rikka0_0
*    2014.4.47
*/

#include <stdio.h>
#include <stdlib.h>
#define QUARTER_ROOT_3 216.5
#define QUARTER_TOT 375
#define CONSTANT_SCALER 1000
unsigned char cosxFF[91]={255,254,254,254,254,254,253,253,252,251,251,250,249,248,247,246,245,243,242,241,239,238,236,234,232,
231,229,227,225,223,220,218,216,213,211,208,206,203,200,198,195,192,189,186,183,180,177,173,170,167,163,160,156,153,149,146,142,138,135,131,
127,123,119,115,111,107,103,99,95,91,87,83,78,74,70,65,61,57,53,48,44,39,35,31,26,22,17,13,8,4,0};

int Ua(unsigned int angle)
{
    char sign=1;
    if(angle > 180)
    {
        angle-=180;
        sign=-1;
    }
    if( 0 <= angle && angle < 60)
    {
        if(angle<30)
            return sign*QUARTER_ROOT_3*cosxFF[30-angle]/CONSTANT_SCALER+0;
        else
            return sign*QUARTER_ROOT_3*cosxFF[angle-30]/CONSTANT_SCALER+0;
    }
    else if(60 <= angle && angle < 120)
    {
        if(angle<90)
            return sign*QUARTER_TOT*cosxFF[angle]/CONSTANT_SCALER+0;
        else
            return -sign*QUARTER_TOT*cosxFF[180-angle]/CONSTANT_SCALER+0;
    }
    else if( 120 <= angle && angle <= 180)
    {
        if(angle<150)
            return -sign*QUARTER_ROOT_3*cosxFF[150-angle]/CONSTANT_SCALER+0;
        else
            return -sign*QUARTER_ROOT_3*cosxFF[angle-150]/CONSTANT_SCALER+0;
    }
}
int Ub(unsigned int angle)
{
    if(angle<120)
        return Ua(120-angle);
    else
        return Ua(angle-120);
}
int Uc(unsigned int angle)
{
    if(angle<240)
        return Ua(240-angle);
    else
        return Ua(angle-240);   
}


int main ()
{
    int angle=0;
    char p = 1; //0-Phase voltage 1-Line voltage
   
    FILE* u=fopen("u.txt","wb");
    FILE* v=fopen("v.txt","wb");
    FILE* w=fopen("w.txt","wb");   
    char t[10];
    while( angle <= 360 )
    {
        itoa(Ua(angle)-p*Ub(angle),t,10);
        fputs(t,u);
        fputs("\n",u);
       
        itoa(Ub(angle)-p*Uc(angle),t,10);
        fputs(t,v);
        fputs("\n",v);
       
        itoa(Uc(angle)-p*Ua(angle),t,10);
        fputs(t,w);
        fputs("\n",w);
       
        angle+=1;
    }
   
    fclose(u);
    fclose(v);
    fclose(w);
    system("Pause");
}
